package com.application.lucky.widget.popupwindow;

import android.app.ActionBar;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.application.lucky.Lucky;
import com.application.lucky.R;
import com.application.lucky.adapter.FriendSearchAdapter;
import com.application.lucky.bean.jsonBean.FriendBean;
import com.application.lucky.bean.jsonBean.FriendListbean;
import com.application.lucky.config.Config;
import com.application.lucky.manager.ContactsManager;
import com.application.lucky.request.nav.UrlManager;
import com.application.mylibrary.utils.DensityUtil;
import com.qunar.im.ui.view.recyclerview.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;

public class HomeSearchPop extends PopupWindow implements View.OnClickListener {
    View ll;
    private Context context;
    private View conentView;

    private PublishSubject<String> mPublishSubject;
    private DisposableObserver<List<FriendBean>> mDisposableObserver;
    private CompositeDisposable mCompositeDisposable;
    private EditText mEtHomeSearch;
    private TextView mTvHomeSearchCancel;
    private ImageView mIvHomeSearchDelete;
    private RecyclerView mRclView;
    private FriendSearchAdapter adapter;
    private View noDataView;

    public HomeSearchPop(Context context) {
        super(context);

        this.context = context;

        initView();
        initListener();
    }

    private void initListener() {
        mIvHomeSearchDelete.setOnClickListener(this);
        mTvHomeSearchCancel.setOnClickListener(this);
        mEtHomeSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    mIvHomeSearchDelete.setVisibility(View.VISIBLE);
                } else {
                    mRclView.setVisibility(View.VISIBLE);
                    noDataView.setVisibility(View.GONE);
                    adapter.setNewData(new ArrayList<FriendBean>());
                    mIvHomeSearchDelete.setVisibility(View.GONE);
                }
                mPublishSubject.onNext(s.toString());
            }
        });
        mEtHomeSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    mPublishSubject.onNext(mEtHomeSearch.getText().toString());
                    return true;
                }
                return false;
            }
        });
        mEtHomeSearch.setImeOptions(EditorInfo.IME_ACTION_NONE);
        mPublishSubject = PublishSubject.create();
        mDisposableObserver = new DisposableObserver<List<FriendBean>>() {

            @Override
            public void onNext(List<FriendBean> s) {
                if (s.size() <= 0) {
                    noDataView.setVisibility(View.VISIBLE);
                    mRclView.setVisibility(View.GONE);
                } else {
                    noDataView.setVisibility(View.GONE);
                    mRclView.setVisibility(View.VISIBLE);
                    adapter.setNewData(s);
                }

            }

            @Override
            public void onError(Throwable throwable) {

            }

            @Override
            public void onComplete() {

            }
        };
        mPublishSubject.debounce(500, TimeUnit.MILLISECONDS).filter(new Predicate<String>() {

            @Override
            public boolean test(String s) throws Exception {

                return s.length() > 0;
            }

        }).switchMap(new Function<String, ObservableSource<List<FriendBean>>>() {

            @Override
            public ObservableSource<List<FriendBean>> apply(String query) throws Exception {
                return getSearchObservable(query);
            }

        }).observeOn(AndroidSchedulers.mainThread()).subscribe(mDisposableObserver);
        mCompositeDisposable = new CompositeDisposable();
        mCompositeDisposable.add(mDisposableObserver);
    }

    private Observable<List<FriendBean>> getSearchObservable(final String query) {
        return Observable.create(new ObservableOnSubscribe<List<FriendBean>>() {

            @Override
            public void subscribe(final ObservableEmitter<List<FriendBean>> observableEmitter) throws Exception {
                List<FriendListbean.FriendListBean> search = ContactsManager.getInstance().search(query);
                List<FriendBean> strings = new ArrayList<>();
                for (FriendListbean.FriendListBean friendListBean : search) {
                    FriendBean user = friendListBean.getUser();
                    if (user != null) {
                        FriendBean friendBean = new FriendBean();
                        friendBean.setNickName(user.getNickName());
                        friendBean.setHeadPic(UrlManager.getHeadPic(user.getHeadPic()));
                        friendBean.setUserId((long) friendListBean.getUserId());
                        strings.add(friendBean);
                    }
                }
                Log.d("SearchActivity", "结束请求，关键词为：" + query);
                observableEmitter.onNext(strings);
                observableEmitter.onComplete();
            }
        }).subscribeOn(Schedulers.io());
    }

    private void initView() {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (inflater != null) {
            conentView = inflater.inflate(R.layout.pop_home_search_layout, null);
        }
        noDataView = conentView.findViewById(R.id.tv_no_date);
        ll = conentView.findViewById(R.id.ll);
        mEtHomeSearch = (EditText) conentView.findViewById(R.id.et_home_search);
        mTvHomeSearchCancel = (TextView) conentView.findViewById(R.id.tv_home_search_cancel);
        mIvHomeSearchDelete = (ImageView) conentView.findViewById(R.id.iv_home_search_delete);
        mRclView = (RecyclerView) conentView.findViewById(R.id.rcl_view);
        mRclView.setLayoutManager(new LinearLayoutManager(context));
        adapter = new FriendSearchAdapter(R.layout.item_friend_adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                int size = adapter.getData().size();
                if (size <= 1) {
                    return;
                }

                FriendBean friendBean = (FriendBean) adapter.getData().get(position);
                mEtHomeSearch.setText(friendBean.getNickName());
            }
        });
        mRclView.setAdapter(adapter);
        this.setWidth(ActionBar.LayoutParams.MATCH_PARENT);
        this.setHeight(ActionBar.LayoutParams.MATCH_PARENT);
        this.setFocusable(true);
        this.setBackgroundDrawable(new BitmapDrawable());
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
//        this.setAnimationStyle(R.style.popwin_add_product_style);
        this.setOutsideTouchable(true);

        setContentView(conentView);

//        setAnimationStyle(R.style.tagsAnim);


    }


    public void show(View v) {
        try {
            mEtHomeSearch.setText("");
//                showAtLocation(v, Gravity.TOP, 0, 0);
            showAsDropDown(v, 0, DensityUtil.dp2px(Lucky.getApplication(), -44));
//                showAtLocation(v, Gravity.TOP, 0, 0);
        } catch (Exception e) {

        }

        if (ll != null) {
            ll.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ll.setBackgroundColor(Color.parseColor("#4d000000"));
                }
            }, 250);
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_home_search_delete:
                mEtHomeSearch.setText("");
                break;
            case R.id.tv_home_search_cancel:
                dismiss();
                break;
        }
    }
}
